<template>
  <view class="container">
    <!-- 头像部分 -->
    <view class="avatar-section">
      <view class="avatar-wrapper" @tap="chooseAvatar">
        <image
          :src="userInfo.avatarUrl || '/static/img/face.jpg'"
          class="avatar"
          mode="aspectFill"
        />
        <view class="avatar-mask">
          <text class="camera-icon">📷</text>
        </view>
      </view>
      <text class="avatar-tip">点击更换头像</text>
    </view>

    <!-- 表单部分 -->
    <view class="form-section">
      <!-- 昵称 -->
      <view class="form-item">
        <view class="label">昵称</view>
        <view class="input-wrapper">
          <!-- #ifdef MP-WEIXIN -->
          <input
            v-model="userInfo.nickName"
            placeholder="请输入昵称"
            class="input"
            maxlength="20"
            type="nickname"
            @blur="onNicknameBlur"
          />
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <button
            class="wx-btn"
            open-type="chooseAvatar"
            @chooseavatar="onChooseAvatar"
          >
            获取微信头像
          </button>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <button class="wx-btn" @tap="getWechatInfo">获取微信信息</button>
          <!-- #endif -->
        </view>
      </view>

      <!-- 老板姓名 -->
      <view class="form-item">
        <view class="label">老板姓名</view>
        <input
          v-model="userInfo.bossName"
          placeholder="请输入老板姓名"
          class="input"
          maxlength="20"
        />
      </view>

      <!-- 单位名称 -->
      <view class="form-item">
        <view class="label">单位名称</view>
        <input
          v-model="userInfo.unit"
          placeholder="请输入单位名称"
          class="input"
          maxlength="50"
        />
      </view>

      <!-- 课题组 -->
      <view class="form-item">
        <view class="label">课题组</view>
        <input
          v-model="userInfo.researchGroup"
          placeholder="请输入课题组"
          class="input"
          maxlength="50"
        />
      </view>

      <!-- 手机号（只读） -->
      <view class="form-item">
        <view class="label">手机号</view>
        <view class="readonly-input">
          {{ userInfo.phone || "未绑定" }}
        </view>
      </view>

      <!-- 密码 -->
      <!-- <view class="form-item">
        <view class="label">密码</view>
        <input
          v-model="userInfo.password"
          placeholder="请输入新密码（不修改请留空）"
          class="input"
          type="password"
          maxlength="20"
        />
      </view> -->
    </view>

    <!-- 保存按钮 -->
    <view class="save-section">
      <button class="save-btn" @tap="saveUserInfo" :loading="loading">
        {{ loading ? "保存中..." : "保存" }}
      </button>
    </view>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo } from "@/common/api/user.js";

export default {
  data() {
    return {
      loading: false,
      userInfo: {
        id: "",
        nickName: "",
        bossName: "",
        unit: "",
        researchGroup: "",
        phone: "",
        password: "",
        openid: "",
        avatarUrl: "",
      },
    };
  },

  onLoad() {
    this.loadUserInfo();
  },

  methods: {
    // 加载用户信息
    async loadUserInfo() {
      try {
        const localUserInfo = uni.getStorageSync("userInfo");
        if (localUserInfo && localUserInfo.id) {
          this.userInfo = { ...this.userInfo, ...localUserInfo };

          // 从服务器获取最新用户信息
          const res = await getUserInfo(localUserInfo.id);
          if (res && res.data && res.data.ok) {
            this.userInfo = { ...this.userInfo, ...res.data.data };
          }
        } else {
          uni.showToast({
            title: "用户信息获取失败",
            icon: "none",
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      }
    },

    // 选择头像
    chooseAvatar() {
      // #ifdef MP-WEIXIN
      // 微信小程序使用 chooseMedia
      uni.chooseMedia({
        count: 1,
        mediaType: ["image"],
        sourceType: ["album", "camera"],
        success: (res) => {
          if (res.tempFiles && res.tempFiles.length > 0) {
            this.userInfo.avatarUrl = res.tempFiles[0].tempFilePath;
          }
        },
      });
      // #endif

      // #ifndef MP-WEIXIN
      // 其他平台使用 chooseImage
      uni.chooseImage({
        count: 1,
        sourceType: ["album", "camera"],
        success: (res) => {
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            this.userInfo.avatarUrl = res.tempFilePaths[0];
          }
        },
      });
      // #endif
    },

    // 微信小程序选择头像
    onChooseAvatar(e) {
      if (e.detail.avatarUrl) {
        this.userInfo.avatarUrl = e.detail.avatarUrl;
        uni.showToast({
          title: "头像更新成功",
          icon: "success",
        });
      }
    },

    // 获取微信信息（非小程序平台）
    getWechatInfo() {
      uni.showToast({
        title: "此功能仅在微信小程序中可用",
        icon: "none",
      });
    },

    // 昵称输入框失焦处理（微信小程序）
    onNicknameBlur(e) {
      // 在微信小程序中，type="nickname" 的输入框会自动处理昵称合规性
      this.userInfo.nickName = e.detail.value;
    },

    // 保存用户信息
    async saveUserInfo() {
      // 验证必填字段
      if (!this.userInfo.nickName.trim()) {
        uni.showToast({
          title: "请输入昵称",
          icon: "none",
        });
        return;
      }
      if (!this.userInfo.bossName.trim()) {
        uni.showToast({
          title: "请输入老板名称",
          icon: "none",
        });
        return;
      }
      if (!this.userInfo.unit.trim()) {
        uni.showToast({
          title: "请输入单位名称",
          icon: "none",
        });
        return;
      }
      if (!this.userInfo.researchGroup.trim()) {
        uni.showToast({
          title: "请输入课题组",
          icon: "none",
        });
        return;
      }

      this.loading = true;

      try {
        // 构建更新数据，排除不需要更新的字段
        const updateData = {
          nickName: this.userInfo.nickName,
          bossName: this.userInfo.bossName,
          unit: this.userInfo.unit,
          researchGroup: this.userInfo.researchGroup,
          avatarUrl: this.userInfo.avatarUrl,
        };

        // 如果输入了新密码，则包含密码字段
        if (this.userInfo.password && this.userInfo.password.trim()) {
          updateData.password = this.userInfo.password;
        }

        const res = await updateUserInfo(this.userInfo.id, updateData);

        if (res && (res.ok || res.success || res.status === "success")) {
          // 更新本地存储的用户信息
          const updatedUserInfo = { ...this.userInfo };
          delete updatedUserInfo.password; // 不存储密码
          uni.setStorageSync("userInfo", updatedUserInfo);

          uni.showToast({
            title: "保存成功",
            icon: "success",
          });

          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.message || "保存失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.showToast({
          title: "保存失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.avatar-section {
  background-color: #fff;
  padding: 40upx 0;
  text-align: center;
  margin-bottom: 20upx;

  .avatar-wrapper {
    position: relative;
    display: inline-block;
    margin-bottom: 20upx;

    .avatar {
      width: 160upx;
      height: 160upx;
      border-radius: 50%;
      border: 4upx solid #f0f0f0;
    }

    .avatar-mask {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 50upx;
      height: 50upx;
      background-color: #f06c7a;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 4upx solid #fff;

      .camera-icon {
        color: #fff;
        font-size: 24upx;
      }
    }
  }

  .avatar-tip {
    color: #999;
    font-size: 28upx;
  }
}

.form-section {
  background-color: #fff;
  margin-bottom: 40upx;
}

.form-item {
  padding: 30upx 40upx;
  border-bottom: 1upx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .label {
    font-size: 32upx;
    color: #333;
    margin-bottom: 20upx;
  }

  .input-wrapper {
    display: flex;
    align-items: center;
    gap: 20upx;

    .input {
      flex: 1;
      font-size: 30upx;
      color: #333;
    }

    .wx-btn {
      padding: 10upx 20upx;
      font-size: 24upx;
      background-color: #f06c7a;
      color: #fff;
      border-radius: 8upx;
      border: none;
      white-space: nowrap;
    }
  }

  .input {
    width: 100%;
    font-size: 30upx;
    color: #333;

    &::placeholder {
      color: #999;
    }
  }

  .readonly-input {
    font-size: 30upx;
    color: #999;
    padding: 10upx 0;
  }
}

.save-section {
  padding: 40upx;

  .save-btn {
    width: 100%;
    height: 88upx;
    background-color: #f06c7a;
    color: #fff;
    font-size: 32upx;
    border-radius: 12upx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;

    &:active {
      background-color: #e55a6a;
    }
  }
}
</style>
